package view;

import Dao.User;
import Dao.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");

        // 获取用户输入的信息
        String username = req.getParameter("username");
        String password1 = req.getParameter("password1");
        String password2 = req.getParameter("password2");
        // 如果有一个没有就注册失败.
        if(username == null || "".equals(username) || password1 == null || "".equals(password1) || password2 == null || "".equals(password2)){
            resp.getWriter().write("<script>alert(\"请输入必要的信息\")</script>\n");
            return;
        }

        UserDao userDao = new UserDao();
        User user = userDao.selectByName(username);
        if(user != null){
            resp.getWriter().write("<script>alert(\"用户名已被使用\")</script>\n");
            return;
        }
        if(!password1.equals(password2)){
            resp.getWriter().write("<script>alert(\"两次输入的密码不一致\")</script>\n");
            return;
        }

        // 设置账号密码 到数据库中
        User user1 = new User();
        user1.setUsername(username);
        user1.setPassword(password1);
        userDao.insert(user1);

        // 注册成功跳转到登录界面
        resp.sendRedirect("login.html");
    }
}
